<template>
  <div>
    <el-row>
      <el-col :span="4">
        采购商:{{title.buyerName}}
      </el-col>
      <el-col :span="4">
        采购单编号:{{title.buyOrderSn}}
      </el-col>
      <el-col :span="4">
        状态:{{$dic.buyerOption[title.status]}}
      </el-col>
      <el-col :span="4">
        支付状态:{{$dic.paymentOption[title.payStatus]}}
      </el-col>
      <el-col :span="6">
        <div>配送日期:
          <el-date-picker
            :editable="false"
            :clearable="false"
            v-model="title.deliveryDate"
            type="date"
            value-format="yyyy-MM-dd"
            class="date-field"
            placeholder="选择日期"
            @change="changeTime">
          </el-date-picker>
        </div>
      </el-col>
      <el-col :span="6">
        <div>批次:
          <el-select v-model="title.buySeq" value-key="value" placeholder="请选择" @change="changebuySeq"
                     class="select-field">
            <el-option
              v-for="item in $dic.buySeqOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </div>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="2">需求信息:</el-col>
      <el-col :span="12">
        <el-input
          type="textarea"
          :autosize="{ minRows: 1, maxRows: 4}"
          maxlength="100"
          @change="modifyFlag=true"
          v-model="title.needNote"></el-input>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="2">备注信息:</el-col>
      <el-col :span="12">
        <el-input
          type="textarea"
          :autosize="{ minRows: 1, maxRows: 4}"
          maxlength="100"
          @change="modifyFlag=true"
          v-model="title.remarks"></el-input>
      </el-col>
      <el-col :span="10">
        <el-button type="primary"
                   :loading="modifyBtnFlag"
                   @click="updateBuyOrder">提交修改
        </el-button>
        <el-button type="primary" round @click="is_excel = true">导入 excel</el-button>
        <div v-if="is_excel">
          <el-dialog title="导入模板" :visible.sync="is_excel" append-to-body width="80%" :before-close="handleClose"
                     class="is_excel">
            <excel_box ref="excelBox" down="1" :data="listData" @select="onSelectList"></excel_box>
          </el-dialog>
        </div>
      </el-col>
    </el-row>
    <el-table
      :data="goodsList"
      stripe
      height="350px"
      style="width: 100%;">
      <el-table-column type="index" width="50" fixed>
      </el-table-column>
      <el-table-column prop="goodsName" label="商品名称" min-width="150" fixed sortable>
      </el-table-column>
      <el-table-column prop="modelName" label="规格" min-width="150" sortable>
      </el-table-column>
      <el-table-column prop="unit" label="单位" min-width="80" sortable>
      </el-table-column>
      <el-table-column prop="goodsNum" label="商品数" min-width="200" sortable>
        <template slot-scope="scope">
          <el-input-number v-if="scope.row.status === '2' || scope.row.status === '1' || scope.row.status ===''"
                           v-model="scope.row.goodsNum" size="mini" :max="1000000" :min="0"
                           @change="modifyFlag=true"></el-input-number>
          <span v-else>{{scope.row.goodsNum}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="marketPrice" label="市场价" min-width="100" sortable>
      </el-table-column>
      <el-table-column prop="buyPrice" label="采购价" min-width="200" sortable>
        <template slot-scope="scope">
          <el-input-number v-if="scope.row.status === '2' || scope.row.status === '1' || scope.row.status ===''"
                           v-model="scope.row.buyPrice" size="mini" :precision="2" :step="0.1" :max="1000000" :min="0"
                           @change="modifyFlag=true"></el-input-number>
          <span v-else>{{scope.row.buyPrice}}</span>
        </template>
      </el-table-column>
      <el-table-column label="上次采购" min-width="150" sortable>
        <template slot-scope="scope">
          <div>时间：{{scope.row.lastDate || '无'}}</div>
          <div v-if="scope.row.lastPrice">价格：￥{{scope.row.lastPrice}}</div>
          <div v-else>价格：无</div>
        </template>
      </el-table-column>
      <el-table-column prop="remarks" label="备注信息" min-width="150">
        <template slot-scope="scope">
          <el-input maxlength="100"
                    v-model="scope.row.remarks"></el-input>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" min-width="80" sortable>
        <template slot-scope="scope">
          {{scope.row.status ? $dic.buyerOption[scope.row.status] : '未提交'}}
        </template>
      </el-table-column>

      <!-- <el-table-column prop="payStatus" label="支付状态" min-width="100" sortable>
        <template slot-scope="scope">
          {{scope.row.payStatus ? $dic.paymentOption[scope.row.payStatus] : '未提交'}}
          {{scope.row.payStatus}}
        </template>
      </el-table-column> -->

      <el-table-column label="操作" min-width="200" fixed="right">
        <template slot-scope="scope">
          <!--                    <el-button type="primary" size="small" @click="handleChangeNum(scope.row)">提交修改</el-button>-->
          <el-button type="primary" size="small" @click="handleDetail(scope.row, scope.$index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-row>
      <el-button
        v-show="showAdd"
        @click="addBuyOrder"
        type="primary" plain
        icon="el-icon-plus">提交商品
      </el-button>
      <el-button
        v-show="!showAdd"
        @click="openShow"
        type="primary" plain
        icon="el-icon-plus">新增商品
      </el-button>
    </el-row>
    <el-row :gutter="20" v-show="showAdd">
      <el-col :span="1.5">
        商品:
      </el-col>
      <el-col :span="4">
        <el-select
          v-model="goodsIndex"
          filterable
          clearable
          default-first-option
          remote
          :remote-method="searchGoodsByName()"
          @change="onGoodsSelectChange()"
          placeholder="输入名称搜索">
          <el-option
            v-for="(item,index) in checkList"
            :key="item.goodsId"
            :label="item.goodsName"
            :value="index"
            @mouseover.native="showPhoto(item.thumbUrl)"
          >
          </el-option>
        </el-select>
      </el-col>
      <el-col :span="1.5">
        规格:
      </el-col>
      <el-col :span="4">
        <el-select
          width="100"
          v-model="goodsModelIndex"
          @change="onGoodsModelSelectChange()"
          placeholder="选择商品规格">
          <el-option
            v-for="(item,index) in spuGoods.modelList"
            :key="item.modelId" :label="item.modelName"
            :value="index">
          </el-option>
        </el-select>
      </el-col>
      <el-col :span="2">
        采购数量:
      </el-col>
      <el-col :span="4">
        <el-input v-model="skuGoods.goodsNum" placeholder="请输入数量" maxlength="10">
        </el-input>
      </el-col>
      <el-col :span="2">
        单位:{{skuGoods.modelUnit}}
      </el-col>
    </el-row>
    <el-row :gutter="20" v-show="showAdd">
      <div v-show="skuGoods.modelPrice">
        <el-col :span="3">
          市场价:{{skuGoods.modelPrice}}&nbsp;元/{{skuGoods.modelUnit || "单位"}}
        </el-col>
        <el-col :span="5">
          采购价:
          <el-input v-model="skuGoods.buyPrice" placeholder="输入采购价" class="input-num" maxlength="10">
          </el-input>&nbsp;元/{{skuGoods.modelUnit}}
        </el-col>
      </div>
      <el-col :span="2">
        备注信息:
      </el-col>
      <el-col :span="5">
        <el-input v-model="skuGoods.remarks" placeholder="请输入备注信息" maxlength="50" style="max-width: 400px">
        </el-input>
      </el-col>
    </el-row>
    <el-row :gutter="20" v-show="showAdd">
      <el-col :span="6" id="show-photo"><img :src="spuGoods.thumbUrl" alt="" width="100px"></el-col>
    </el-row>
  </div>
</template>

<script>
  import Request from "../../request.js";
  import {
    modifyList
  } from "@/api/saleb/modifyList";
  import {
    modifyBuyOrder, editBuyOrder
  } from "@/api/saleb/buyorder";
  import Excel_box from "@/components/pds/common/excel_box";
  import {
    importDetail
  } from '@/api/saleb/importTable';
  import {getGoodsList} from '@/api/goods/goods.js'
  import {getStore, setStore} from "@/util/store";

  export default {
    data: function () {
      return {
        request: new Request(),
        goodsIndex: "",
        checkList: [],
        modelList: [],
        modelPrice:'',
        spuGoods: {
          goodsModelList: []
        },
        skuGoods: {},
        goodsModelIndex: "",
        showAdd: false,
        is_excel: false,
        listData: {},
        modifyFlag: false,
        modifyBtnFlag: false,
      }
    },
    components: {
      Excel_box
    },
    props: {
      goodsList: Array,
      title: {
        type: Object
      }
    },
    created() {
      this.listData = {
        deliveryTime: this.title.deliveryTime,
        buySeq: this.title.buySeq,
        deliveryType: this.title.deliveryType,
        needNote: this.title.needNote,
        buyerName: this.title.buyerName,
        shipFee: this.title.shipFee,
        buyerId: this.title.buyerId
      }
    },
    methods: {
      handleClose(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {
          });
      },
      onSelectList(list) {
        this.$refs.excelBox.btnFlag = true;
        let params = {};
        params.list = list;
        params.buyId = this.title.buyId;
        importDetail(params).then(res => {
          this.$notify({
            title: '提示',
            message: res.data.data,
            duration: 50000
          });
          this.is_excel = false;
        }).catch(err => {
          this.$notify({
            title: '提示',
            message: err,
            duration: 50000
          });
        }).finally(() => {
          // this.purchaseList();
          if (this.$refs.excelBox) {
            this.$refs.excelBox.btnFlag = false;
          }
        })
      },
      //改变配送时间时
      changeTime(value) {
        this.listData.deliveryTime = value;
        this.resetAddGood();
        this.modifyFlag = true;
      },
      changebuySeq(value) {
        this.listData.buySeq = value;
        this.modifyFlag = true;
      },
      handleDetail(item, index) {
        this.$confirm('您确认要删除该商品吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.goodsList.splice(index, 1);
          this.modifyFlag = true;
        })
      },
      searchGoodsByName() {
        // 将row信息传入
        let _this = this;
        return function (searchValue) {
          if (searchValue !== '') {
            let params = {
              goodsName: searchValue,
              deliveryDate: _this.title.deliveryTime
            }
            _this.getGoodsList(params).then(res => {
              _this.checkList = res
            })
          }
        }
      },
      getGoodsList(params) {
        params.size = 20;
        params.current = 1
        params.shopId = this.getStore({name: "shopId"});
        params.buyerId = this.title.buyerId;
        params.buySeq = this.title.buySeq;
        return getGoodsList(params).then(res => {
          if (res.data.code === 0) {
            // console.log(res);
            return res.data.data.records
          } else {
            console.log('商品列表获取错误', res.msg)
          }
          return []
        })
      },
      openShow() {
        this.resetAddGood();
        this.showAdd = true;
      },
      closeShow() {
        this.resetAddGood();
        this.showAdd = false;
      },
      resetAddGood() {
        this.goodsIndex = "";
        this.checkList = [];
        this.modelList = [];
        this.spuGoods = {
          goodsModelList: []
        };
        this.skuGoods = {};
        this.goodsModelIndex = "";
      },
      onGoodsSelectChange() {
        if (typeof this.goodsIndex === 'number') {
          this.spuGoods = this.checkList[this.goodsIndex];
          console.log(this.spuGoods);
          this.goodsModelIndex = 0;
          this.onGoodsModelSelectChange();
        } else {
          this.skuGoods = {};
          this.spuGoods = {
            goodsModelList: []
          };
          this.goodsModelIndex = "";
        }
      },
      onGoodsModelSelectChange() {
        this.skuGoods = this.spuGoods.modelList[this.goodsModelIndex];
        this.skuGoods.goodsName = this.spuGoods.goodsName
      },
      handleChangeNum(item) {
        let regNum = /^[0-9]+(\.[0-9]{1,2})?$/;
        let regPrice = /^[0-9]+(\.[0-9]{1,2})?$/;
        if (!regNum.test(item.goodsNum)) {
          this.$message.error('数量有误,请输入数字,最多2位小数');
          return;
        }
        if (!regPrice.test(item.buyPrice)) {
          this.$message.error('价格有误,请输入数字,最多2位小数');
          return;
        }
        let params = {
          buyDetailSn: item.buyDetailSn,
          buyPrice: item.buyPrice,
          goodsNum: item.goodsNum
        };

        this.changeNum(params);
      },
      // 修改商品数量
      changeNum(params = {}) {
        modifyList(params).then(res => {
          if (res.data.code === 0) {
            this.$message.success('修改成功')
            // this.purchaseList()
          } else {
            this.$message.warning(res.data.msg)
          }
        })
      },
      // 新增商品
      addBuyOrder(params = {}) {
        let item = {
          modelId: this.skuGoods.modelId,
          goodsName: this.skuGoods.goodsName,
          modelName: this.skuGoods.modelName,
          unit: this.skuGoods.modelUnit,
          goodsNum: this.skuGoods.goodsNum,
          marketPrice: this.skuGoods.modelPrice,//modelPrice
          buyPrice: this.skuGoods.buyPrice || this.skuGoods.purchasePrice,
          remarks: this.skuGoods.remarks,
          status: ''
          
        };
       
        if (!item.goodsNum || !item.modelId) {
          this.$message.warning("请选择商品和采购数量")
          return;
        }
        let flag = false;
        let msg = "新增商品 [" + item.goodsName + "], 您确认新增该商品吗？";
        for (let i = 0, len = this.goodsList.length; i < len; i++) {
          if (this.goodsList[i].goodsId === item.goodsId) {
            flag = true;
            break;
          }
        }
        if (flag) {
          msg = "已存在 " + msg;
        }
        this.$confirm(msg, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.goodsList.splice(this.goodsList.length, 0, item);
          this.modifyFlag = true;
        })
      },
      // 修改 采购单信息
      updateBuyOrder() {
        this.modifyBtnFlag = true;
        if (!this.goodsList || this.goodsList.length < 1) {
          this.$message.error("无采购单明细信息");
          this.modifyBtnFlag = false;
          return;
        }
        if (!this.modifyFlag) {
          this.$message.error("未修改信息");
          this.modifyBtnFlag = false;
          return;
        }
        let detailList = this.goodsList.map(item => {
          return {
            goodsModelId: item.modelId,
            goodsNum: item.goodsNum,
            buyPrice: item.buyPrice,
            remarks: item.remarks || null,
          }
        });
        let params = {
          buyOrderSn: this.title.buyOrderSn,
          buyerId: this.title.buyerId,
          deliveryDate: this.title.deliveryDate,
          buySeq: this.title.buySeq,
          needNote: this.title.needNote,
          remarks: this.title.remarks,
          shipFee: this.title.shipFee,
          deliveryType: this.title.deliveryType,
          detailList: detailList
        };
        console.log(params);
        editBuyOrder(params).then(res => {
          console.log(res);
          if (res.data.code === 0 && res.data.data) {
                    this.$message.success('订单修改成功');
                    this.modifyFlag = false;
                    // this.purchaseList();
                } else {
                    this.$message.warning(res.data.msg);
                }
                this.modifyBtnFlag = false;
        })
      },
      // purchaseList() {
      //   this.request.purchaseList({buyId: this.title.buyId, pageSize: 100}).then(res => {
      //     if (res.code === 200) {
      //       this.changeGoodsList(res.ext.list);
      //     } else {
      //       this.changeGoodsList([]);
      //       this.$message.warning(res.msg)
      //     }
      //   }).catch(err => {
      //     this.$message.error(err)
      //   })
      // },
      changeGoodsList(list) {
        this.$emit('change-list', list);
      },
      showPhoto(url) {
        this.spuGoods.thumbUrl = url;
      }
    }
  }
</script>

<style scoped lang="scss">
  .el-row {
    margin-top: 10px;
  }

  .input-num {
    width: 100px;
  }

  .date-field {
    width: 150px;
  }

  .select-field {
    width: 150px;
  }

  .el-date-editor.el-input, .el-select {
    width: 70% !important;
    margin-left: 10px;
  }

  .upload-demo {
    display: inline-block;
    margin-left: 10px;
  }
</style>
